﻿using UnityEngine;
using System.Collections;

namespace play {
	public class Main : MonoBehaviour {
		
		public static int leftEnemyCount = 8;	//!!!必须>3 每关16只怪，开始生成3只
		int _leftEnemyCount = 8;
		public static int aliveEnemyCount = 0;	// 每生成1只怪 +1
		public static int life = 2;				// 剩余生命数
		public static int MAX_LEVEL = 10;		// 一共10关
		// 复活位置
		public Vector3 rebornPos = new Vector3 (9, 1, 0);

		int level;		// 当前关数
		Config cfg;
		int[,] maps;
		ArrayList arrBlank = new ArrayList();

		// 非移动设备隐藏摇杆
		void Awake() {
			if (Application.platform != RuntimePlatform.Android) {
				GameObject[] objs = GameObject.FindGameObjectsWithTag("TOUCH_ONLY");
				foreach (GameObject obj in objs) {
					Destroy(obj);
				}
			}
		}

		// Use this for initialization
		void Start () {
			level = Config.level;

			// 初始化配置数据
			cfg = new Config ();
			// 加载地图数据
			maps = loadMaps ();

			// 加载关卡
			loadLevel ();
		}

		public void loadNextLevelAfterSec(float s) {
			Config.level++;
			if (level == 10) {
				// 通关了
				StartCoroutine (toWin (0.5f));
			}

			StartCoroutine (loadNextLevel (s));
		}

		IEnumerator toWin(float s) {
			yield return new WaitForSeconds (s);

			Application.LoadLevel("win");
		}

		IEnumerator loadNextLevel(float s) {
			yield return new WaitForSeconds (s);

			Application.LoadLevel("play");
		}

		void loadLevel() {
			play.PlayerState.rebornTime = Time.time;

			// 播放音频
			AudioSource audioSource = GetComponent<AudioSource> ();
			audioSource.clip = Resources.Load("mp3/play") as AudioClip;
			audioSource.Play ();

			// 绘制地图块
			for (int i = 0; i < 13; i++) {
				for (int j = 0; j < 13; j++) {
					
					GameObject obj = Instantiate (Resources.Load("prefab/" + cfg.codeToName(maps[i + 13 * level, j])),
					             new Vector3 ((j + 1) * 2 - 1, (i + 1) * 2 - 1, 0),
					             Quaternion.identity
					) as GameObject;
					// 记录上半部分的空地
					if (i > 6 && "blank".Equals(cfg.codeToName(maps[i + 13 * level, j]))) {
						arrBlank.Add(obj);
					}
				}
			}
			// 绘制一圈河流
			Object river = Resources.Load ("prefab/iron");
			for (int i = 0; i < 13; i++) {
				// 上边
				Instantiate (river,
				             new Vector3 ((i + 1) * 2 - 1, 27, 0),
				             Quaternion.identity
				             );
				// 下边
				Instantiate (river,
				             new Vector3 ((i + 1) * 2 - 1, -1, 0),
				             Quaternion.identity
				             );
				// 左边
				Instantiate (river,
				             new Vector3 (-1, (i + 1) * 2 - 1, 0),
				             Quaternion.identity
				             );
				// 右边
				Instantiate (river,
				             new Vector3 (27, (i + 1) * 2 - 1, 0),
				             Quaternion.identity
				             );
			}

			// 生成怪物
			genEnemies ();
		}

		int[,] loadMaps() {
			string data = ((TextAsset)Resources.Load("data/map_data")).text;
			string[] tmpArr = data.Split(new char[]{';'}, System.StringSplitOptions.RemoveEmptyEntries);
			int[,] maps = new int[tmpArr.Length,13];
			string[] tmpArr2;
			
			for (int i = 0; i < tmpArr.Length; i++) {
				tmpArr2 = tmpArr[i].Split(new char[]{','}, System.StringSplitOptions.RemoveEmptyEntries);
				
				for (int j = 0; j < tmpArr2.Length; j++) {
					maps[i,j] = int.Parse(tmpArr2[j]);
				}
			}

			return maps;
		}

		// Update is called once per frame
		void Update () {
			// back键 返回 index
			if ((Application.platform == RuntimePlatform.Android && Input.GetKeyDown(KeyCode.Escape)) || Input.GetKeyDown(KeyCode.Escape)) {
				Application.LoadLevel("index");
			}
		}

		// s秒后复活
		public void rebornAfterSec(float s) {
			StartCoroutine (reborn (s));
		}

		IEnumerator reborn(float s) {
			yield return new WaitForSeconds (s);
			
			//print (playerState.isImmune);
			GameObject obj = Instantiate (Resources.Load("prefab/p1tank"), rebornPos, Quaternion.identity) as GameObject;
			PlayerState playerState = obj.transform.GetComponent<PlayerState> ();
			playerState.isImmune = true;	// 无敌
			print ("复活");///
			playerState.isAlive = true;
			PlayerState.rebornTime = Time.time;
		}

		public void gameoverAfterSec(float s) {
			StartCoroutine (gameover (s));
		}

		IEnumerator gameover(float s) {
			yield return new WaitForSeconds (s);

			Application.LoadLevel("gameover");
		}

		void genEnemies() {
			leftEnemyCount = _leftEnemyCount;
			aliveEnemyCount = 0;

			for (int i = 0; i < 3; i++) {
				StartCoroutine(genEnemy (0.5f));
			}
		}

		public void genEnemyAfterSec(float s) {
			StartCoroutine(genEnemy (s));
		}

		IEnumerator genEnemy(float s) {
			yield return new WaitForSeconds (s);

			// 在上半部分找一块空地
			int index = Common.rand (0, arrBlank.Count - 1);
			GameObject obj = (GameObject)(arrBlank[index]);
			Instantiate (Resources.Load("prefab/enemy1"), obj.transform.position, Quaternion.identity);
			aliveEnemyCount++;
			leftEnemyCount--;
		}
	}
}